package dao;

import db.DatabaseManager;
import model.SaleRecord;
import java.sql.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class SaleDao {

    public List<SaleRecord> getAllSales() {
        List<SaleRecord> sales = new ArrayList<>();
        String sql = "SELECT * FROM sales ORDER BY sale_time DESC";

        try (Connection conn = DatabaseManager.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            while (rs.next()) {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime saleTime = LocalDateTime.parse(rs.getString("sale_time").replace(" ", "T"));

                SaleRecord sale = new SaleRecord(
                        rs.getString("id"),
                        rs.getString("computer_id"),
                        rs.getString("customer_id"),
                        rs.getInt("quantity"),
                        rs.getDouble("total_amount")
                );
                sale.setSaleTime(saleTime);
                sales.add(sale);
            }
        } catch (SQLException e) {
            System.out.println("查询销售记录失败: " + e.getMessage());
        }
        return sales;
    }

    public void addSale(SaleRecord sale) {
        String sql = "INSERT INTO sales(id, computer_id, customer_id, quantity, total_amount, sale_time) VALUES(?,?,?,?,?,?)";

        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            pstmt.setString(1, sale.getId());
            pstmt.setString(2, sale.getComputerId());
            pstmt.setString(3, sale.getCustomerId());
            pstmt.setInt(4, sale.getQuantity());
            pstmt.setDouble(5, sale.getTotalAmount());
            pstmt.setString(6, sale.getSaleTime().format(formatter));
            pstmt.executeUpdate();

        } catch (SQLException e) {
            System.out.println("添加销售记录失败: " + e.getMessage());
        }
    }
}